package cn.snorlaxzjt.LBSserver.service;

import cn.snorlaxzjt.LBSserver.mapper.MessageMapper;
import cn.snorlaxzjt.LBSserver.mapper.UserMapper;
import cn.snorlaxzjt.LBSserver.po.entity.Message;
import cn.snorlaxzjt.LBSserver.po.entity.User;
import cn.snorlaxzjt.LBSserver.po.page.ChatInfoPage;
import cn.snorlaxzjt.LBSserver.util.MessageUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class MessageService {

    @Resource
    MessageMapper messageMapper;

    @Resource
    UserService userService;

    @Resource
    UserMapper userMapper;


    public void addMessage(com.farsunset.cim.sdk.server.model.Message message, Integer visited) {
        Message messageInfo = MessageUtil.getMessageInfo(message);
        messageMapper.addMessage(messageInfo, visited);
    }


    public List<Message> getMessage(Integer id) {
        Integer currentUserId = userService.getCurrentUserId();
        return messageMapper.getMessage(currentUserId, id);
    }

    public List<ChatInfoPage> getList() {
        Integer currentUserId = userService.getCurrentUserId();
        List<Message> list = messageMapper.getList(currentUserId);
        List<ChatInfoPage> ans = new ArrayList<>();
        List<Integer> friendIdList = new ArrayList<>();
        if(list == null || list.size() == 0) return new ArrayList<>();
        for(Message m : list){
            int id;
            if(m.getSender() == userService.getCurrentUserId()){
                id = m.getReceiver();
            }else {
                id = m.getSender();
            }
            if(!friendIdList.contains(id)){
                friendIdList.add(id);
                ChatInfoPage page = new ChatInfoPage();
                page.setId(id);
                page.setLastMessage(m.getContent());
                ans.add(page);
            }
        }
        List<User> info = userMapper.selectBatchIds(friendIdList);
        Map<Integer,User> map = info.stream().collect(Collectors.toMap(User::getId,Function.identity()));
        for(ChatInfoPage p:ans){
            User u = map.get(p.getId());
            p.setAvatar(u.getAvatar());
            p.setNickname(u.getUsername());
        }
        return ans;
    }
}
